/**
 * Created by zhuyongjie on 2017/12/18.
 */

/**
 * 查询字典表
 * @param dictType
 * @param tagId
 * @param defaultValue
 * @param nullable 是否添加控制
 */
function initDict(dictType, tagId, defaultValue,nullable,option) {
    $.ajax({
        type: "POST",
        url:   "/tdm-web/tdm/matterBase/queryDictData",
        data: {
            dictType: dictType,
            startSize: '',
            endSize: ''
        },
        dataType: "json",
        success: function (data) {
            if (!String.isUndefined(data)) {
                var returnObj = data.returnObject;
                if (!String.isUndefined(returnObj)) {
                    var rows = returnObj.rows;
                    if (!String.isUndefined(rows)) {
                        if(nullable){
                            rows.unshift({"dictCode": "", "dictName": "--请选择--"});
                        }
                        $(tagId).combobox({
                            'valueField': 'dictCode',
                            'textField': 'dictName',
                            'data': rows
                        });
                        if(!String.isUndefined(option) && !String.isUndefined(option.onLoadSuccess)){
                            $(tagId).combobox({
                                onLoadSuccess:option.onLoadSuccess
                            });
                        }
                        if(!String.isUndefined(option) && !String.isUndefined(option.onChange)){
                            $(tagId).combobox({
                                onChange:option.onChange
                            });
                        }
                        if(!String.isUndefined(option) && !String.isUndefined(option.formatter)){
                            $(tagId).combobox({
                                formatter:option.formatter
                            });
                        }

                        if(!String.isUndefined(option) && !String.isUndefined(option.onSelect)){
                            $(tagId).combobox({
                                onSelect:option.onSelect
                            });
                        }
                        $(tagId).combobox('setValue', defaultValue);

                    }
                }

            }
        },
        error: function (data, textstatus) {
            layer.alert("加载税种失败", {closeBtn: 0, shift: 4});
        }
    });
}

/**
 * 字典表组合树
 * @param dictType
 * @param tagId
 * @param defaultValue
 */
function initDictTree(dictType, tagId, defaultValue,opt) {
    $.ajax({
        type: "POST",
        url: "/ledger-web/ledger/manager/listDictTreeData",
        data: {
            dictType: dictType,
            startSize: '',
            endSize: ''
        },
        dataType: "json",
        success: function (data) {
            if (!String.isUndefined(data)) {
                var returnObj = data.returnObject;
                if (!String.isUndefined(returnObj)) {
                    var rows = returnObj.rows;
                    if (!String.isUndefined(rows)) {
                        if(rows.isJSON){
                            rows = JSON.parse(rows);
                        }
                        var treeData = convert(rows);
                        // rows.unshift({"id": "", "text": "--请选择--"});
                       // $("#" + tagId).combotree('loadData',treeData)
                        $("#" + tagId).combotree({
                           data : treeData
                        });
                        $("#" + tagId).combotree('setValues', defaultValue);
                        if(!String.isUndefined(opt)){
                            $("#" + tagId).combotree(opt);
                        }

                    }
                }

            }
        },
        error: function (data, textstatus) {
            layer.alert("加载数据失败", {closeBtn: 0, shift: 4});
        }
    });
}

/**
 * 查询字典表
 * @param dictType
 * @param tagId
 * @param defaultValue
 */
function initDictMsg(dictType, tagId, defaultValue ,errorMsg) {
    $.ajax({
        type: "POST",
        url: "/tdm-web/tdm/matterBase/queryDictData",
        data: {
            dictType: dictType,
            startSize: '',
            endSize: ''
        },
        dataType: "json",
        success: function (data) {
            if (!String.isUndefined(data)) {
                var returnObj = data.returnObject;
                if (!String.isUndefined(returnObj)) {
                    var rows = returnObj.rows;
                    if (!String.isUndefined(rows)) {
                        rows.unshift({"dictCode": "", "dictName": "--请选择--"});
                        $("#" + tagId).combobox({
                            'valueField': 'dictCode',
                            'textField': 'dictName',
                            'data': rows
                        });
                        $("#" + tagId).combobox('setValue', defaultValue);
                    }
                }


            }
        },
        error: function (data, textstatus) {
            layer.alert(errorMsg, {closeBtn: 0, shift: 4});
        }
    });
}

/**
 * 初始化行业信息
 * @param tagId
 * @param defaultValue
 */
function initIndustry(tagId,defaultValue,option){
    $.ajax({
        type: "POST",
        url: path + "/ledger/manager/listIndustryData",
        data: {
            id:'000000'
        },
        dataType: "json",
        success: function (data) {
            if (!String.isUndefined(data)) {
                var returnObj = data.returnObject;
                if (!String.isUndefined(returnObj)) {
                    var rows = returnObj.rows;
                    if (!String.isUndefined(rows)) {
                        if(rows.isJSON){
                            rows = JSON.parse(rows);
                        }
                        $(tagId).combobox({
                            'valueField': 'id',
                            'textField': 'text',
                            'data': rows
                        });
                        if(!String.isUndefined(option) && !String.isUndefined(option.onLoadSuccess)){
                            $(tagId).combobox({
                                onLoadSuccess:option.onLoadSuccess
                            });
                        }
                        if(!String.isUndefined(option) && !String.isUndefined(option.onChange)){
                            $(tagId).combobox({
                                onChange:option.onChange
                            });
                        }
                        $(tagId).combobox('setValue', defaultValue);
                    }
                }

            }
        },
        error: function (data, textstatus) {
            layer.alert("加载税种失败", {closeBtn: 0, shift: 4});
        }
    });
}

/**
 * 初始化行业信息树
 * @param tagId
 * @param option
 */
function initIndustryTree(tagId,option){
    if(String.isUndefined(option)){
        option = {
            defaultValue : '',
            multiple : false
        };

    }
    var treeUrl = path + "/ledger/manager/listIndustryDataTree";
    $.ajax({
        type: "POST",
        url: treeUrl,
        data: {
            id:'000000'
        },
        dataType: "json",
        success: function (data) {
            if (!String.isUndefined(data)) {
                var returnObj = data;
                if (!String.isUndefined(returnObj)) {
                    var rows = returnObj;
                    if (!String.isUndefined(rows)) {
                            rows.unshift({
                                "id": "000000",
                                "text": "行业信息",
                                "state":"open",
                                "pid": "999999"
                            });
                            var treeData = convert(rows);
                            $(tagId).combotree ({
                                data:treeData,
                                editable:false,
                                multiple:option.multiple,
                                cascadeCheck:false,
                                panelWidth:400,
                                panelHeight:300,
                                onBeforeExpand:function(node) {
                                    $(tagId).combotree("tree").tree("options").url = treeUrl + "?id=" + node.id;
                                }
                            });
                            $(tagId).combotree('setValue', String.isUndefined(option.defaultValue) ? '' : option.defaultValue) ;


                    }
                }

            }
        },
        error: function (data, textstatus) {
            layer.alert("加载行业失败", {closeBtn: 0, shift: 4});
        }
    });
}




/**
 * 转换成树json
 * @param rows
 * @returns {Array}
 */
function convert(rows){
    //是否存在父节点
    function exists(rows, pid){
        for(var i=0; i<rows.length; i++){
            if (rows[i].id == pid) return true;
        }
        return false;
    }

    var nodes = [];
    // get the top level nodes
    for(var i=0; i<rows.length; i++){
        var row = rows[i];
        if (!exists(rows, row.pid)){
           /* nodes.push({
                id:row.id,
                text:row.text,
                state:row.state,
                pid:row.pid
            });*/
           nodes.push(row);
        }
    }

    var toDo = [];
    for(var i=0; i<nodes.length; i++){
        toDo.push(nodes[i]);
    }
    while(toDo.length){
        var node = toDo.shift();	// the parent node
        // get the children nodes
        for(var i=0; i<rows.length; i++){
            var row = rows[i];
            if (row.pid == node.id){
                /*var child = {
                    id:row.id,
                    text:row.text,
                    state:row.state,
                    pid:row.pid
                };*/
                var child = row;
                if (node.children){
                    node.children.push(child);
                } else {
                    node.children = [child];
                }
                toDo.push(child);
            }
        }
    }
    return nodes;
}

/**
 * 组织机构combotree
 * @param tag
 * @param option
 */
function initOrgTree(tagId,option){
    var orgUrl = path + "/ledger/manager/listOrg";
    if(String.isUndefined(option)){
        option = {
            multiple : false,
            editable : false,
            defaultValue : '',
            defaultTag :false
        }
    }

    $.ajax({
        type: "POST",
        url: orgUrl,
        data: {
            id:curUserOrgCode,
            root:'Y'
        },
        dataType: "json",
        success: function (data) {
            if (!String.isUndefined(data)) {
                var returnObj = data;
                if (!String.isUndefined(returnObj)) {
                    var rows = returnObj;
                    if (!String.isUndefined(rows)) {
                        //组装树
                        var treeData = convert(rows);
                        var tree = {};
                        if(!String.isUndefined(option.defaultTag) && option.defaultTag){
                            tree = [{
                                "id": "DEF",
                                "text": "默认",
                                "state": "open",
                                "pid": "0",
                                "children" : treeData
                            }];
                        }else{
                            tree = treeData;
                        }
                        $(tagId).combotree ({
                            data:tree,
                            editable:String.isUndefined(option.editable) ? false : option.editable,
                            multiple:String.isUndefined(option.multiple) ? false : option.multiple,
                            cascadeCheck:false,
                            panelWidth:600,
                           // panelHeight:500,
                            onBeforeExpand:function(node) {
                                $(tagId).combotree("tree").tree("options").url = orgUrl + "?id=" + node.id;
                            }
                        });
                        $(tagId).combotree('setValue', option.defaultValue);


                    }
                }

            }
        },
        error: function (data, textstatus) {
            layer.alert("加载行业失败", {closeBtn: 0, shift: 4});
        }
    });
}

/**
 * 初始化台账组
 * @param tagId
 * @param defaultValue
 */
function initGroupCombobox(tagId,defaultValue,option){
    if(String.isUndefined(option)){
        option = {
            tdclasscode : ''
        }
    }
    var url = path + "/ledger/manager/listGroupIndex";
    $.ajax({
        type: "POST",
        url: url,
        data: {
            pageNo:'',
            pageSize:'',
            tdclasscode : String.isUndefined(option.tdclasscode) ? '' : option.tdclasscode
        },
        dataType: "json",
        success: function (data) {
            if (!String.isUndefined(data)) {
                var returnObj = data.returnObject;
                if (!String.isUndefined(returnObj)) {
                    var rows = returnObj.rows;
                    if (!String.isUndefined(rows)) {
                        // rows.unshift({"dictCode": "", "dictName": "--请选择--"});
                        $(tagId).combobox({
                            'valueField': 'LDGTYPECODE',
                            'textField': 'LDGTYPENAME',
                            'data': rows
                        });
                       // $(tagId).combobox('setValue', defaultValue);
                        $(tagId).combobox('select',defaultValue);

                    }
                }

            }
        },
        error: function (data, textstatus) {
            layer.alert("加载台账组失败", {closeBtn: 0, shift: 4});
        }
    });
}


/**
 * 重置搜索条件
 */
function btnReset() {
    var searchBar = $("#searchForm").find("input[id],select[id]");
    $.each(searchBar, function (index, item) {
        var className = $(item).attr("class");
        var tagId = $(item).attr("id");
        //不清除标识
        var noClear = $(item).attr("noClear");
        if (className && className.indexOf("easyui-combobox") != -1) {
            if(!noClear || noClear == 'N'){
                $("#" + tagId).combobox("setValue", "");
            }

        }else if(className && className.indexOf("easyui-textbox") != -1){
            var title = $(item).attr("title");
            if(!noClear || noClear == 'N') {
                $("#" + tagId).textbox('setValue', '');
            }
            if(!String.isUndefined(title) && !String.isEmpty(title)){
                $("#" + tagId).textbox({
                    prompt : title
                });
            }
        }else if(className && className.indexOf("easyui-numberbox") != -1){
            if(!noClear || noClear == 'N') {
                $("#" + tagId).numberbox('setValue', '');
            }
        } else if(className && className.indexOf("easyui-combotree") != -1){
            if(!noClear || noClear == 'N') {
                $("#" + tagId).combotree('setValue', '');
            }
        }else {
            if(!noClear || noClear == 'N') {
                $("#" + tagId).val("");
            }
        }
        if (className && className.indexOf("Wdate") != -1) {
            $("#" + tagId).off();
        }

    })
}

/**
 * 转换成大写
 * @param value
 * @returns {string}
 */
function toUpperCase(value) {
    return value.toUpperCase();
}
/**
 * 字段自动转换成大写
 */
function columnUpperCase(column) {
    $("#"+column).textbox('textbox').bind('keyup',function (e) {
        var  value = this.value;
        value = toUpperCase(value);
        $("#"+column).textbox('setValue',value)
    });
}
/**
 * 字段自动下拉
 */
function autoDropCombobox(column){
    $("#"+column).combobox('textbox').bind('focus',function(){
        $("#"+column).combobox('showPanel');
    });
}

/**
 * 金额数据格式化方法(格式：123,456,789.00)
 * s: 数据
 * n: 几位小数
 **/
function formartNumber(s, n) {
    n = (n && n > 0 && n <= 20) ? n : 2;
    s = (s + "").replace(/\,/g, ""); //替换所有","号为""
    if (!/^(\-?\d+)(\.\d+)?$/.test(s) || s == "") {
        return parseFloat("0").toFixed(n);
    }
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + ""; //用""替换全部非[\d\.-]，并转换成n小数位浮点数
    var f = "";
    if (s.indexOf("-") != -1) {
        f = s.substring(0, 1);
        s = s.substring(1, s.length);
    }
    var l = s.split(".")[0].split("").reverse();//reverse颠倒数组的顺序
    r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return f + t.split("").reverse().join("") + "." + r;
}

/**
 * 打开弹窗
 * @param url url
 * @param title 标题
 * @param fullFlag 是否全屏true/false
 * @param width 宽度【数值】
 * @param height 高度【数值】
 * @param id
 * @param endFun 结束返回函数
 * @param cancelFun 结束返回函数
 */
function openWin(url,title,fullFlag,width,height,id,endFun,cancelFun) {
    if(String.isUndefined(cancelFun)){
        cancelFun = function (index, layero) {
            top.layer.close(index);
        }
    }
    var index = top.layer.open({
        type: 2,
        id: id,//不能有固定id，否则多层次弹窗失败
        title: title,
        area: [ width + 'px', height + 'px'],
        shadeClose: false,
        shade: 0.3,
        maxmin: true,
        content: url,
        zIndex: top.layer.zIndex,//重点1,
        success: function (layero) {
            top.layer.setTop(layero); //重点2
        },
        end: endFun,
        cancel: cancelFun
    });
    if(fullFlag){
        top.layer.full(index);
    }

}

/**
 * 清除表外
 * @param opt
 */
function deleteOutside(opt) {

    var options = {
        defId : '',//台账定义id
        cellCode : 'DEF',//单元格id
        isLedger : false,//是否是台账设置，默认否
        onBefore : function () {},//删除表外前事件
        callBack : function () {}//删除表外后处理事件
    };
    if (opt && $.isEmptyObject(opt) == false) {
        //覆盖默认值，使用传值参数
        opt = $.extend(true,options, opt);
    } else {
        opt = options;
    }
    //执行删除前执行事件
    opt.onBefore();
    if(opt.isLedger){
        //清除表外
        if (checkBaseCell()) {
            cleanOutside();
            changeFlag = true;
            var baseCellId = $(baseCell).attr('id');
            var params = new Object();
            params.defId = defId;
            params.cellCode = baseCellId;
            params.saveType = stepType.clearOut;
            saveDataByStep(params,opt);
        }
    }else{
        var params = new Object();
        params.defId = opt.defId;
        params.cellCode = opt.cellCode;
        params.saveType = stepType.clearOut;
        saveDataByStep(params,opt);
    }

}

/**
 * 设置表外
 * @param opt
 */
function openOutsideWindow(opt){
    var options = {
        defId : '',//台账定义id
        cellCode : 'DEF',//单元格id
        title : '表外关系设置',//标题
        isLedger : false,//是否是台账设置，默认否
        formula : '',//表达式
        formulaText : '',//表达式文本
        formulaSql : '',//表达式SQL
        outOrgCode:'',
        outTaxPerd:'',
        callBack : function(){},//回调函数
        onBefore : function () {}//调用表外之前处理函数
    };
    if (opt && $.isEmptyObject(opt) == false) {
        //覆盖默认值，使用传值参数
        opt = $.extend(true,options, opt);
    } else {
        opt = options;
    }
    //处理预制条件
    opt.onBefore();
    var outsideUrl = "/ledger-web/ledger/manager/outSetting/loadOutsideSettingPage";
    outsideUrl += "?defId=" + opt.defId;
    outsideUrl += "&cellCode=" + opt.cellCode;
    outsideUrl += "&outOrgCode=" + opt.outOrgCode;
    outsideUrl += "&outTaxPerd=" + opt.outTaxPerd;

    setGlobalVariable('otherFormulaText', opt.formula);//表达式text
    setGlobalVariable('otherFormulaValue', opt.formulaText);//表达式code
    setGlobalVariable('otherFormulaSql', opt.formulaSql);//表达式SQL

    openWin(outsideUrl, opt.title, true, 1300, 600, 'dataItemDef',function () {
            layerEndFuunc(opt);
    },
        function (index,layero) {
        //获取弹出层值
        var outChangeFlag = $(layero).find("iframe")[0].contentWindow.changeFlag;
        if(outChangeFlag){
            //调用弹出层方法
            $(layero).find("iframe")[0].contentWindow.beforeClose();
            return false;
        }else{
            top.layer.close(index);
        }
    });
}

/**
 * @Method      layerEndFuunc
 * @Param       mod
 * @Description [表外窗体End处理事件]
 * @Author      zhuyongjie
 * @Version     1.0
 * @Date        2018/4/2 14:14
 */
function layerEndFuunc(opt) {

    var otherFormulaText = getGlobalVariable('otherFormulaText');//表达式text
    var otherFormulaValue = getGlobalVariable('otherFormulaValue');//表达式code
    var otherFormulaSql = getGlobalVariable('otherFormulaSql');//表达式SQL
    var successed = getGlobalVariable('successed');
    if (!String.isEmpty(otherFormulaText)) {
        if (opt.isLedger) {
            $('#formula').textbox('setValue', otherFormulaText);
            $(baseCell)
                .attr(outsideFormula, otherFormulaValue)
                .attr(outsideFormulaText, otherFormulaText)
                .attr(outsideFormulaSql, otherFormulaSql)
                .css({
                    'background-color': '#' + outsideColorObj.backgroudColor
                }).parent("td").css({'background-color': '#' + outsideColorObj.backgroudColor});
        } else {
            setGlobalVariable("formulaText", otherFormulaText);
        }
        //执行回调函数
        opt.callBack();
        var params = new Object();
        params.defId = opt.defId;
        params.cellCode = opt.cellCode;
        params.calcExp = otherFormulaValue;
        params.calcExpText = otherFormulaText;
        params.calcExpSql = otherFormulaSql;
        params.saveType = stepType.outType;
        if (successed && successed == 'true') {
            saveDataByStep(params);
            if (opt.isLedger) {
                changeFlag = true;
            }
        }

    }
}

//单步保存类型
var stepType = {
    winType : 'winType',//表内
    extType : 'extType',//表间
    colorType : 'colorType',//样式
    outType : 'outType',//表外
    clearWin : 'clearWin',//清除表内
    clearExt : 'clearExt',//清除表间
    clearColor : 'clearColor',//清除样式
    clearOut : 'clearOut',//清除表外
    clearAll : 'clearAll'//清除所有
};

/**
 * @Method      saveDataByStep
 * @Param       params
 * @param       opt 执行成功回调函数参数
 * @Description []
 * @Author      zhuyongjie
 * @Version     1.0
 * @Date        2018/4/2 14:21
 */
function saveDataByStep(params,opt){
    //保存设置
    $.ajax({
        type: "POST",
        url:  '/ledger-web/ledger/manager/form/saveDataByStep',
        data:params,
        dataType: "json",
        success: function callback(data) {
            if (data) {
                var code = data.code;
                if (code == "0000") {
                    changeFlag = false;
                    $.messager.show({
                        title:'保存提醒',
                        msg:'保存成功',
                        showType:'slide',
                        timeout : 2
                    });
                    if(!String.isUndefined(opt) && !String.isUndefined(opt.callBack)){
                        //保存后执行事件
                        opt.callBack();
                    }
                } else {
                    $.alert("default", "error", data.msg);
                }
            }

        },
        error: function (data, textstatus) {
            $.alert("default", "error", data.msg);
        }
    });
}